import numpy as np
from local_search_operators.two_opt import two_opt

def tsp_apply_local_search(new_population, cities, elite_size, ls_intensity):
    """
    TSP特定的局部搜索应用逻辑
    
    参数:
    new_population: 当前种群
    cities: 城市坐标
    elite_size: 精英个体数量
    ls_intensity: 局部搜索强度
    
    返回:
    应用局部搜索后的种群
    """
    # 计算适应度
    from problems.TSP.fitness import calculate_fitness
    new_fitness_values = calculate_fitness(new_population, cities)
    
    # 找到精英个体（适应度最高的前elite_size个个体）
    elite_indices = np.argsort(new_fitness_values)[-elite_size:]
    
    # 对每个精英个体应用two_opt局部搜索
    for idx in elite_indices:
        improved_individual, improved_distance = two_opt(
            new_population[idx], cities, ls_intensity
        )
        new_population[idx] = improved_individual
    
    return new_population